//
//  Sprite.mm
//  Prism
//
//  Created by Bas du Pre on 20-05-11.
//  Copyright 2011 UU. All rights reserved.
//

#include "global.h"
#if PRISM_OS_IOS
#include "ios_global.h"

#include "Sprite.h"
#include "Director.h"

using namespace Prism;

void Sprite::native_init() {
    
}

void Sprite::native_loadSprite() {
    //IOS_sprite = [CCSprite spriteWithTexture:_textureFrame->texture()->native_toCCTexture2D() rect:native_prismRectToCGRect(_textureFrame->rect())];
    // native_toCCTexture2D fixes @2x automagically
    _textureFrame->texture()->native_toCCTexture2D();
    
    NSString* filename = [NSString stringWithUTF8String: _textureFrame->texture()->file()->filename()]; 
    NSString* ext = [filename pathExtension];
    NSString* p = [filename stringByDeletingPathExtension];
    NSString* hd = [NSString stringWithFormat:@"%@-hd.%@", p, ext];
    if (!Prism::File::exists([hd cStringUsingEncoding:[NSString defaultCStringEncoding]]))
    {
        if ([[CCDirector sharedDirector] contentScaleFactor] == 2.0) {
            if ([p hasSuffix: @"@2x"]) {
                native_scale = 1;       
            }
        }
    } else {
        native_scale = 1;
    }
    IOS_sprite = [CCSprite node];
    native_setCCNode(IOS_sprite);
    native_updateSprite();
}

void Sprite::native_updateSprite() {
    CCTexture2D* newTexture = _textureFrame->texture()->native_toCCTexture2D();
    if ([IOS_sprite texture] != newTexture) {
        [IOS_sprite setTexture:newTexture];
    }
    
    if (native_isRetinaNode()) {
        [IOS_sprite setTextureRect:native_prismRectToCGRect(_textureFrame->rect())];
    } else { 
        CGRect r = native_prismRectToCGRect(_textureFrame->rect());
        [IOS_sprite setTextureRectInPixels:r rotated:NO untrimmedSize:r.size];
    }
    
    // TODO: update nativeScale if this is a @2x or not anymore
}

Prism::Rect Sprite::native_boundingBox() {
    Prism::Rect rect;
    CGRect ccRect = [IOS_sprite boundingBox];
    
    rect.origin.x = ccRect.origin.x;
    rect.origin.y = ccRect.origin.y;
    rect.size.width = ccRect.size.width;
    rect.size.height = ccRect.size.height;
    
    rect.origin = native_correctPosition(rect.origin);
    rect.origin.y -= rect.size.height;
    
    return rect;
}


#endif
